# -*- coding: utf-8 -*-
from django.core.files import File
from django.core.exceptions import ValidationError
from projectapp.models import file_upload_data
import os,uuid,imghdr,requests,json
from PIL import Image
from io import StringIO
from io import BytesIO
import unicodedata

class save_file1:
    def __init__(self,file,title,type,label,username):
        self.file=file
        self.title=title
        self.type=type
        self.label=label
        self.username=username
        self.return_data = []
        self.type_name=''
    def get_file_upload_msg(self):
        name = "MaterialLibrary"
        url = 'http://10.129.8.19:8080/api/uploadStream.action'
        print(self.file)
        for item in self.file:
            payload = {'name': name, 'file_name': item.name}
            files = {'image': ("." + item.name.split('.')[-1], item.read(), item.content_type)}
            r = requests.post(url, files=files, data=payload)
            self.return_data.append(r.text)
        self.type_name=unicodedata.normalize('NFKD', self.type).encode('ascii', 'ignore')
    def save_msg_to_mysql(self):
        same_id=str(uuid.uuid1())
        # try:
        for i in self.return_data:
            for j in json.loads(i)['payload']:
                try:
                    image_request_result = requests.get('http://10.129.8.19:8080/%s'%(j['address'][0].replace('\\', '/')))
                    image = Image.open(BytesIO(image_request_result.content))
                    width, height = image.size
                except:
                    width, height = ['NA','NA']
                post=file_upload_data.objects.create(
                    title=self.title,
                    type=self.type,
                    label=self.label,
                    path=j['address'][0],
                    msg=json.loads(i)['msg'],
                    response_status=json.loads(i)['code'],
                    name=j['name'][0],
                    sql_id=j['id'][0],
                    img_size=j['size'][0],
                    img_width=width,
                    img_height=height,
                    same_id=same_id,
                    username=self.username,
                    file_format=j['name'][0].split(".")[-1],
                )
                post.save()
        # except BaseException:
        #     print('server error')
        #     return "server error"